package com.tianpengtech.admin;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.HashKit;
import com.jfinal.upload.UploadFile;
import com.tianpengtech.common.GlobalConfigConstant;
import com.tianpengtech.common.model.account.Account;
import com.tianpengtech.common.plugin.shiro.ext.ClearShiro;
import com.tianpengtech.common.util.JsonUtil;
import com.tianpengtech.common.util.QiNiuUtil;

import java.io.FileInputStream;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;


@RequiresAuthentication
public class AdminCommonController extends Controller {

    private static Logger logger = Logger.getLogger(AdminCommonController.class);
    public void index() {

        renderTemplate("index_new.html");
    }


    @ClearShiro
    public void login() {

        renderTemplate("login.html");
    }


    @Before(POST.class)
    @ClearShiro
    public void doLogin() {
        try {
            String userName = getPara(Account.USERNAME, GlobalConfigConstant.DEFAULT_VALUE_EMPTY);
            String userPass = getPara(Account.USERPASS, GlobalConfigConstant.DEFAULT_VALUE_EMPTY);
            userPass = HashKit.md5(userPass+GlobalConfigConstant.SALT_KEY);
            logger.debug(userPass);
            UsernamePasswordToken token = new UsernamePasswordToken(userName, userPass);
            token.setRememberMe(false);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            renderJson(JsonUtil.printSuccess("登录成功..."));
        } catch (AuthenticationException e) {
            renderJson(JsonUtil.printError("数据库中没有相关记录"));
        }
    }

    @RequiresAuthentication
    public void logout() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        this.redirect("/admin/login");
    }

    
    public void upload() throws Exception {
        UploadFile upfile=getFile();
        try {
            String upload = QiNiuUtil.upload(new FileInputStream(upfile.getFile()));
            upfile.getFile().delete();
            renderText(upload);
        } catch (Exception e) {
            throw e;
        }

    }
    
    
    public void welcome() {

        renderTemplate("welcome.html");
    }


    public void forbidden(){

        renderTemplate("403.html");
    }
}
